package com.hl.ruoyilkshop.service.impl;

import com.hl.ruoyilkshop.service.ISearchService;
import com.hl.ruoyilkshop.service.IGoodsService;
import com.hl.ruoyilkshop.service.IGoodsClassService;
import com.hl.ruoyilkshop.domain.Goods;
import com.hl.ruoyilkshop.domain.GoodsClass;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// Elasticsearch相关导入
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IGoodsClassService goodsClassService;

    @Override
    public AjaxResult searchGoods(String keyword, int pageNum, int pageSize) {
        try {
            SearchRequest searchRequest = new SearchRequest("goods1");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

            // 构建搜索查询
            sourceBuilder.query(QueryBuilders.multiMatchQuery(keyword, "goodsName", "categoryName"));

            // 分页
            sourceBuilder.from((pageNum - 1) * pageSize);
            sourceBuilder.size(pageSize);

            // 排序（按相关性）
            sourceBuilder.sort("_score", SortOrder.DESC);

            searchRequest.source(sourceBuilder);

            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

            List<Map<String, Object>> results = new ArrayList<>();
            for (SearchHit hit : response.getHits().getHits()) {
                Map<String, Object> source = hit.getSourceAsMap();
                source.put("score", hit.getScore());
                results.add(source);
            }

            Map<String, Object> data = new HashMap<>();
            data.put("rows", results);
            data.put("total", response.getHits().getTotalHits().value);
            data.put("pageNum", pageNum);
            data.put("pageSize", pageSize);

            return AjaxResult.success(data);

        } catch (IOException e) {
            return AjaxResult.error("搜索失败：" + e.getMessage());
        }
    }

    @Override
    public AjaxResult addGoodsToIndex(Long goodsId) {
        try {
            // 从数据库获取商品信息
            Goods goods = goodsService.selectGoodsByGoodsId(goodsId);
            if (goods == null) {
                return AjaxResult.error("商品不存在");
            }

            // 获取商品分类信息
            String categoryName = "";
            if (goods.getClassId() != null) {
                GoodsClass goodsClass = goodsClassService.selectGoodsClassById(goods.getClassId());
                if (goodsClass != null) {
                    categoryName = goodsClass.getName();
                }
            }

            // 构建ES文档
            Map<String, Object> document = new HashMap<>();
            document.put("goodsId", goods.getGoodsId());
            document.put("businessId", goods.getBusinessId());
            document.put("goodsName", goods.getGoodsName());
            document.put("classId", goods.getClassId());
            document.put("categoryName", categoryName);
            document.put("goodsPrice", goods.getGoodsPrice() != null ? goods.getGoodsPrice().doubleValue() : null);
            document.put("goodsPoint", goods.getGoodsPoint());
            document.put("goodsPointType", goods.getGoodsPointType());
            document.put("goodsDiscountType", goods.getGoodsDiscountType());
            document.put("goodsKillType", goods.getGoodsKillType());
            document.put("goodsGroupType", goods.getGoodsGroupType());
            document.put("goodsGroupPrice", goods.getGoodsGroupPrice() != null ? goods.getGoodsGroupPrice().doubleValue() : null);
            document.put("goodsDiscount", goods.getGoodsDiscount() != null ? goods.getGoodsDiscount().doubleValue() : null);
            document.put("goodsMiaosha", goods.getGoodsMiaosha() != null ? goods.getGoodsMiaosha().doubleValue() : null);
            document.put("goodsStatus", goods.getGoodsStatus());
            document.put("goodsNumber", goods.getGoodsNumber());
            document.put("goodsImg", goods.getGoodsImg());
            document.put("goodsVideo", goods.getGoodsVideo());
            document.put("businessClassId", goods.getBusinessClassId());
            document.put("goodsVirtual", goods.getGoodsVirtual());
            document.put("unit", goods.getUnit());
            document.put("createTime", goods.getCreateTime());
            document.put("updateTime", goods.getUpdateTime());

            // 创建索引请求
            IndexRequest indexRequest = new IndexRequest("goods1")
                    .id(goodsId.toString())
                    .source(document, XContentType.JSON);

            client.index(indexRequest, RequestOptions.DEFAULT);

            return AjaxResult.success("商品已成功添加到搜索索引");

        } catch (IOException e) {
            return AjaxResult.error("添加商品到索引失败：" + e.getMessage());
        }
    }

    @Override
    public AjaxResult deleteGoodsFromIndex(Long goodsId) {
        try {
            // 创建删除请求
            DeleteRequest deleteRequest = new DeleteRequest("goods1", goodsId.toString());
            client.delete(deleteRequest, RequestOptions.DEFAULT);

            return AjaxResult.success("商品已从搜索索引中删除");

        } catch (IOException e) {
            return AjaxResult.error("从索引删除商品失败：" + e.getMessage());
        }
    }

    @Override
    public AjaxResult syncAllGoodsToIndex() {
        try {
            // 获取所有商品
            List<Goods> allGoods = goodsService.selectGoodsList(new Goods());
            
            if (allGoods.isEmpty()) {
                return AjaxResult.success("没有商品需要同步");
            }

            // 批量操作
            BulkRequest bulkRequest = new BulkRequest();
            int successCount = 0;
            int failCount = 0;

            for (Goods goods : allGoods) {
                try {
                    // 获取商品分类信息
                    String categoryName = "";
                    if (goods.getClassId() != null) {
                        GoodsClass goodsClass = goodsClassService.selectGoodsClassById(goods.getClassId());
                        if (goodsClass != null) {
                            categoryName = goodsClass.getName();
                        }
                    }

                    // 构建ES文档
                    Map<String, Object> document = new HashMap<>();
                    document.put("goodsId", goods.getGoodsId());
                    document.put("businessId", goods.getBusinessId());
                    document.put("goodsName", goods.getGoodsName());
                    document.put("classId", goods.getClassId());
                    document.put("categoryName", categoryName);
                    document.put("goodsPrice", goods.getGoodsPrice() != null ? goods.getGoodsPrice().doubleValue() : null);
                    document.put("goodsPoint", goods.getGoodsPoint());
                    document.put("goodsPointType", goods.getGoodsPointType());
                    document.put("goodsDiscountType", goods.getGoodsDiscountType());
                    document.put("goodsKillType", goods.getGoodsKillType());
                    document.put("goodsGroupType", goods.getGoodsGroupType());
                    document.put("goodsGroupPrice", goods.getGoodsGroupPrice() != null ? goods.getGoodsGroupPrice().doubleValue() : null);
                    document.put("goodsDiscount", goods.getGoodsDiscount() != null ? goods.getGoodsDiscount().doubleValue() : null);
                    document.put("goodsMiaosha", goods.getGoodsMiaosha() != null ? goods.getGoodsMiaosha().doubleValue() : null);
                    document.put("goodsStatus", goods.getGoodsStatus());
                    document.put("goodsNumber", goods.getGoodsNumber());
                    document.put("goodsImg", goods.getGoodsImg());
                    document.put("goodsVideo", goods.getGoodsVideo());
                    document.put("businessClassId", goods.getBusinessClassId());
                    document.put("goodsVirtual", goods.getGoodsVirtual());
                    document.put("unit", goods.getUnit());
                    document.put("createTime", goods.getCreateTime());
                    document.put("updateTime", goods.getUpdateTime());

                    // 添加到批量请求
                    IndexRequest indexRequest = new IndexRequest("goods1")
                            .id(goods.getGoodsId().toString())
                            .source(document, XContentType.JSON);
                    bulkRequest.add(indexRequest);
                    successCount++;

                } catch (Exception e) {
                    failCount++;
                    System.err.println("处理商品 " + goods.getGoodsId() + " 时出错: " + e.getMessage());
                }
            }

            // 执行批量操作
            if (bulkRequest.numberOfActions() > 0) {
                BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
                
                if (bulkResponse.hasFailures()) {
                    return AjaxResult.error("批量同步完成，但有部分失败。成功: " + successCount + ", 失败: " + failCount);
                } else {
                    return AjaxResult.success("批量同步完成，共同步 " + successCount + " 个商品");
                }
            } else {
                return AjaxResult.success("没有商品需要同步");
            }

        } catch (IOException e) {
            return AjaxResult.error("同步所有商品到索引失败：" + e.getMessage());
        }
    }
}